#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
图片清理服务
定期清理临时文件，防止磁盘占满
"""

import os
import time
import threading
import logging
from pathlib import Path
from config import Config

logger = logging.getLogger(__name__)

class CleanupService:
    def __init__(self):
        self.running = False
        self.cleanup_thread = None
    
    def cleanup_old_files(self):
        """清理超过指定时间的文件"""
        current_time = time.time()
        cleaned_count = 0
        freed_size = 0
        
        for folder in [Config.UPLOAD_FOLDER, Config.RESULT_FOLDER]:
            if not os.path.exists(folder):
                continue
            
            for file_path in Path(folder).glob('*'):
                if not file_path.is_file():
                    continue
                
                # 检查文件年龄
                file_age = current_time - file_path.stat().st_mtime
                if file_age > Config.CLEANUP_AGE:
                    try:
                        file_size = file_path.stat().st_size
                        file_path.unlink()
                        cleaned_count += 1
                        freed_size += file_size
                        logger.info(f"清理旧文件: {file_path.name} (年龄: {file_age:.0f}秒)")
                    except Exception as e:
                        logger.error(f"删除文件失败: {file_path.name}, 错误: {e}")
        
        if cleaned_count > 0:
            logger.info(f"清理完成: 删除 {cleaned_count} 个文件，释放 {freed_size / 1024 / 1024:.2f} MB")
    
    def cleanup_task_files(self, task_id: str):
        """清理特定任务的文件（任务完成后立即调用）"""
        if not Config.IMMEDIATE_CLEANUP:
            return
        
        deleted = []
        for folder in [Config.UPLOAD_FOLDER, Config.RESULT_FOLDER]:
            if not os.path.exists(folder):
                continue
            
            for file_path in Path(folder).glob(f'*{task_id}*'):
                try:
                    file_path.unlink()
                    deleted.append(file_path.name)
                    logger.info(f"即时清理: {file_path.name}")
                except Exception as e:
                    logger.error(f"删除任务文件失败: {file_path.name}, 错误: {e}")
        
        if deleted:
            logger.info(f"任务 {task_id} 清理完成，删除文件: {', '.join(deleted)}")
    
    def _cleanup_loop(self):
        """定时清理循环"""
        logger.info(f"图片清理服务启动，清理间隔: {Config.CLEANUP_INTERVAL}秒")
        
        while self.running:
            try:
                self.cleanup_old_files()
            except Exception as e:
                logger.error(f"定时清理异常: {e}")
            
            # 等待下一次清理
            time.sleep(Config.CLEANUP_INTERVAL)
    
    def start(self):
        """启动清理服务"""
        if not Config.CLEANUP_ENABLED:
            logger.info("图片清理服务已禁用")
            return
        
        if self.running:
            logger.warning("图片清理服务已在运行")
            return
        
        self.running = True
        self.cleanup_thread = threading.Thread(target=self._cleanup_loop, daemon=True)
        self.cleanup_thread.start()
        logger.info("图片清理服务已启动")
    
    def stop(self):
        """停止清理服务"""
        if not self.running:
            return
        
        self.running = False
        if self.cleanup_thread:
            self.cleanup_thread.join(timeout=5)
        logger.info("图片清理服务已停止")

# 全局清理服务实例
cleanup_service = CleanupService()

